package com.datastructure.test.iptonum;

public class IPtoNum {

    public static void main(String[] args) {

    }

    public String IPtoNum (String ip) {
        // write code here
        long ans = 0L;
        String[] ips = ip.split("\\.");
        for(int i = 3; i >= 0; --i) {
            ans += Integer.parseInt(ips[3-i]) * (1L << (i*8));
        }
        return Long.toString(ans);
    }

    public String IPtoNum1 (String ip) {
        // write code here
        StringBuilder sb = new StringBuilder("");
        String[] strs = ip.split("\\.");
        for (String str : strs) {
            sb.append(DecimalToBinary(Integer.parseInt(str)));
        }
        String tmpStr = new String(sb);
        char[] chrs = tmpStr.toCharArray();
        long ans = 0l;
        int account = 0;
        for (int i = chrs.length - 1; i > -1; i--) {
            if (Integer.parseInt(chrs[i] + "") == 1) {
                ans += ((long) Math.pow(2, account));
            }
            account++;
        }
        return String.valueOf(ans);
    }

    public String DecimalToBinary(int num) {
        StringBuilder sb = new StringBuilder("");
        while (0 != num) {
            sb.append(num % 2);
            num /= 2;
        }
        sb.reverse();
        StringBuilder ans = new StringBuilder(new String(sb));
        while (ans.length() != 8) {
            ans.insert(0, "0");
        }
        return ans.toString();
    }
}
